<template>
  <GroupPage :has-content-title="false" class="p-0">
    <template #group>
      <SpinSkeleton v-show="tableLoading || viewList.length > 0" :loading="tableLoading">
        <div
          v-for="(el, i) in viewList"
          :key="el.viewId"
          class="py-2 px-4 mb-2 cursor-pointer hover-container h-16 flex flex-row items-center"
          :class="[curIndex === i ? 'bg-opacity-10 bg-color-active' : 'bg-header']"
          @click="handleCheckModal(el, i)"
        >
          <div class="mb-1" :class="[curIndex === i ? 'text-color-active' : 'text-color-main']">
            <Icon type="icon-zongbu" class="text-xl" />
            {{ el.viewName }}
          </div>
          <!-- <div class="text-color-secondary text-sm">{{ el.description }}</div> -->
        </div>
      </SpinSkeleton>
      <SlEmpty v-show="!tableLoading && viewList.length === 0" :description="emptyText"></SlEmpty>
    </template>
    <template #content>
      <div class="pl-7 pt-7 pr-2.5">
        <SearchForm
          ref="searchIns"
          class="!mb-0"
          :keyword-search-data="[{ label: '点位名称', key: 'searchText' }]"
          :show-add-btn="false"
          :select-data="selectData"
          @search="handleSearchFn"
        >
          <template #extraButtons>
            <PermissionBtn
              v-show="![0, -1].includes(curIndex) && !isView"
              :oper-type="OperPermissionType.MANAGE"
              :btn-props="{ danger: true, type: 'primary' }"
              :disabled-mes="selectedAttrKeys && selectedAttrKeys.length > 0 ? null : '请选择要移除的点位'"
              @click="handleBatchRemovePoint"
            >
              移除点位
              <template #icon>
                <Icon type="icon-shanchu" class="" />
              </template>
            </PermissionBtn>
            <PermissionBtn
              v-show="![0, -1].includes(curIndex) && !isView"
              class="ml-4"
              :oper-type="OperPermissionType.MANAGE"
              :btn-props="{ type: 'primary' }"
              @click="handleBatchAddPoint"
            >
              添加点位
              <template #icon>
                <Icon type="icon-tianjia" class="" />
              </template>
            </PermissionBtn>
          </template>
        </SearchForm>
      </div>
      <div class="flex-1 overflow-hidden px-7 pb-0">
        <SlTable
          :columns="columns"
          row-key="equipmentTypeAttributeId"
          :data-source="tableData"
          :loading="tableLoading"
          :pagination="pagination"
          :scroll="{ x: 'auto' }"
          :search-model="searchModel"
          :ignore-keys="['operationView', 'equipmentTypeId', 'userView']"
          :row-selection="rowSelection"
        >
          <template #bodyCell="{ column, record }">
            <!-- <div v-if="column.dataIndex === 'attributeName'" class="flex flex-row items-center">
              <div class="pr-4" style="font-size: 0" @mousedown="sortStart($event, index)">
                <Icon type="icon-tuodong" class="text-2xl cursor-move !text-color-secondary" />
              </div>
              {{ record.attributeName }}
            </div> -->
            <div v-if="column.dataIndex === 'attributeLevel'">
              {{ AttributeLevel[record.attributeLevel] || "--" }}
            </div>
            <div v-if="column.dataIndex === 'readWriteType'">
              {{ ReadWriteType[record.readWriteType] || "--" }}
            </div>
            <div v-if="column.dataIndex === 'dataType'">
              {{ DataType[record.dataType] || "--" }}
            </div>
          </template>
        </SlTable>
      </div>
    </template>
    <EquipmentTypeAttrSelectModal
      v-model:value="selectedDefaultIds"
      v-model:visible="funcVisible"
      :view-code="viewCode"
      :equipment-type-id="options.equipmentTypeId"
      @success-fn="reloadTable"
    />
  </GroupPage>
</template>
<script lang="ts" setup>
import { onMounted, ref, watch, nextTick, provide, computed } from "vue";
import { Api, attrPage, equipmentGroupPage, changeEquipmentTypeAttributesViewBatch } from "/@/api/aiot/equipmentType";
import {
  AttributeLevel,
  ReadWriteType,
  DataType,
  ParEquipmentAttrItem,
  AttrViewReq,
} from "/@/api/aiot/equipmentType/models";
import { useCURD } from "/@/hooks/useCURD";
import { OperPermissionType } from "/@/api/aiot/role/models";
import PermissionBtn from "/@/components/PermissionBtn.vue";
import { useEmptyText } from "/@/hooks/useEmptyText";
import { useRowDragSort } from "/@/hooks/useRowDragSort";
import { SearchFormKeywordKey, SelectItem } from "/@/types/components";
import { EquipmentFunctionModalOptions } from "/@/api/aiot/equipment/models";
import { DataNode } from "ant-design-vue/es/tree";
import { loopItem } from "/@/utils/treeData";
import { message } from "ant-design-vue";
import InfoModal from "../../InfoModal";

const { emptyText, modelForEmptyText } = useEmptyText();
// 定义props
const props = withDefaults(
  defineProps<{
    options: EquipmentFunctionModalOptions;
    activeTab: string;
    isView?: boolean;
  }>(),
  {
    isView: false,
  }
);
const keyword = ref<string>("");
// 已选功能id
const selectedDefaultIds = ref<string[]>([]);
// 已选或者禁止选择的点位
const disabledIds = ref<string[]>([]);
// 点位数据
const templateData = ref<DataNode[]>([]);
// 添加点位弹框visible
const funcVisible = ref<boolean>(false);
provide(SearchFormKeywordKey, keyword);
// 当前选中视图的code
const viewCode = computed(() => {
  if (curIndex.value > -1) {
    return viewList[curIndex.value].viewCode;
  } else {
    return "";
  }
});
// 搜索下拉筛选数据
const selectData = ref<SelectItem[]>([
  {
    label: "参数分组",
    value: "",
    key: "equipmentParamGroupsId",
    isTreeSelect: true,
    containerWidth: 180,
    props: {
      treeData: [],
      fieldNames: { label: "equipmentParamGroupsName", value: "equipmentParamGroupsId" },
    },
  },
]);
// 当前选择的监听项目
const curIndex = ref<number>(-1);
// 临时监控项目数组
/**
 * 30f93ab7-ebd8-11ed-b499-0242ac150002   工厂视图
  30f940fe-ebd8-11ed-b499-0242ac151112   运维视图
  30f9536e-ebd8-11ed-b499-0242ac152222  用户视图
 * 
 */
const viewList = [
  { viewName: "厂商视图", viewId: "30f93ab7-ebd8-11ed-b499-0242ac150002", viewCode: "all" },
  { viewName: "运维视图", viewId: "30f940fe-ebd8-11ed-b499-0242ac151112", viewCode: "operationView" },
  { viewName: "客户视图", viewId: "30f9536e-ebd8-11ed-b499-0242ac152222", viewCode: "userView" },
];
// 监控项目CURD
const { tableData, tableLoading, reloadTable, curd, searchModel, pagination } = useCURD<ParEquipmentAttrItem>({
  getPageUrl: Api.attrPage,
  loadOnMounted: false,
});
const selectedAttrKeys = ref<string[]>([]);
const rowSelection = {
  onChange: (selectedRowKeys: string[], selectedRows: ParEquipmentAttrItem[]) => {
    selectedAttrKeys.value = selectedRowKeys;
  },
  getCheckboxProps: (record: ParEquipmentAttrItem) => ({}),
};
onMounted(async () => {
  let req = await equipmentGroupPage(props.options.equipmentTypeId);
  reloadTable({ model: { equipmentTypeId: props.options.equipmentTypeId } });
  // 执行初始化数据
  reset();
  let selectTreeProps = selectData.value[0].props;
  if (selectTreeProps && req) {
    selectTreeProps.treeData = req?.records || [];
    selectTreeProps.treeData.unshift({ equipmentParamGroupsName: "全部", equipmentParamGroupsId: "" });
  }
});
// 初始化数据
function reset() {
  // 清空table已选
  selectedAttrKeys.value = [];
}
// 排序模块
const { sortStart } = useRowDragSort({
  adjustNow: true,
  onSort(curRecord, targetRecord, isUp, curIndex, targetIndex) {
    console.log(curRecord, targetRecord, isUp, curIndex, targetIndex);
  },
  data: tableData,
});
// columns
const columns = [
  {
    title: "点位名称",
    dataIndex: "attributeName",
    width: 120,
  },
  {
    title: "显示名称",
    dataIndex: "attributeDisplayName",
    width: 120,
  },
  {
    title: "参数分组",
    dataIndex: "equipmentParamGroupsName",
    ellipsis: true,
    width: 120,
  },
  {
    title: "参数级别",
    dataIndex: "attributeLevel",
    ellipsis: true,
    width: 120,
  },
  {
    title: "读写类型",
    dataIndex: "readWriteType",
    ellipsis: true,
    width: 120,
  },
  {
    title: "数据类型",
    dataIndex: "dataType",
    ellipsis: true,
    width: 120,
  },
  {
    title: "值状态说明",
    dataIndex: "attributeDesc",
    ellipsis: true,
    width: 120,
  },
];
// 点击视图事件
function handleCheckModal(el, i) {
  keyword.value = "";
  curIndex.value = i;
  let model = {
    operationView: viewCode.value === "operationView" ? true : null,
    userView: viewCode.value === "userView" ? true : null,
    searchText: "",
  };

  reloadTable({ model });
}
// 搜索点位列表
async function handleSearchFn(model) {
  console.info("model", model);
  reloadTable({ model });
}
// 移除点位
async function handleBatchRemovePoint() {
  InfoModal.confirm({
    content: "您确定要移除已选点位吗？",
    async onOk() {
      let data: AttrViewReq = { equipmentTypeAttributeIds: selectedAttrKeys.value };
      // 当前选中的视图code
      if (viewCode.value !== "all" && viewCode.value) {
        data[viewCode.value] = false;
      }
      let req = await changeEquipmentTypeAttributesViewBatch(data);
      if (req) {
        message.success("操作成功");
        reloadTable();
        // 清空已选的数据
        selectedAttrKeys.value = [];
      }
    },
  });
}
// 添加点位
async function handleBatchAddPoint() {
  let model = {
    searchText: "",
  };
  let req = await attrPage({ current: 1, size: 999, model });
  let attrList = req?.records;
  let sum = 0;
  disabledIds.value = [];
  loopItem<ParEquipmentAttrItem>(attrList || [], (item) => {
    item.key = item.equipmentTypeAttributeId as string;
    item.title = item.attributeName;
    if (item[viewCode.value]) {
      item.equipmentTypeAttributeId ? disabledIds.value.push(item.equipmentTypeAttributeId) : null;
    }
    sum++;
  });
  templateData.value = (attrList as any) || [];
  funcVisible.value = true;
}
</script>
<style lang="less" scoped>
:deep(.ant-spin-nested-loading) {
  height: calc(100% - 60px);
  overflow: auto;
}
.view-content {
  height: calc(100% - 155px);
}
.view-container {
  height: calc(100% - 61px) !important;
}
:deep(.ant-collapse) {
  // width: 100%;
  background-color: #fff;
}
</style>
